import os
import re
import shutil
import commands
import _mysql
import hashlib
import logger

# Analyze project.
def analyze_metrics(project, revision, url, db, folder):
	analyze_code_metrics(project, revision, url, db, folder)
	analyze_filemetrics(project, revision, url, db, folder)

# Get code metrics:
def analyze_code_metrics(project, revision, url, db, folder):
	logger.printinfo("Analyzing code")
	phand = os.popen("cloc "+folder)

	# read output from the command
	while 1:
		line = phand.readline()
		if line == "": break
		# Find the sum of the code calculations with regex.
		m = re.search('SUM:.*?(?P<FILES>[0-9]+).*? (?P<BLANK>[0-9]+).*? (?P<COMMENT>[0-9]+).*? (?P<CODE>[0-9]+)', line)
		if m is not None:
			files 	= m.group("FILES")
			blank 	= m.group("BLANK")
			comment = m.group("COMMENT")
			code 	= m.group("CODE")
		
			db.insertmetric(project, revision, url, files, blank, comment, code)
			phand.close()
			return

	phand.close()
	return
	
# Code metrics by file:
def analyze_filemetrics (project, revision, url, db, folder):
	logger.printinfo("Analyzing files")
	phand = os.popen("cloc --by-file --sql=1 " + folder)

	# read output from the command
	while 1:
		line = phand.readline()
		if line == "": break
		m = re.search('\',\ \'(?P<LANG>.*?)\',\ \'(?P<FILE>.*?)\',\ (?P<BLANK>[0-9]+),\ (?P<COMMENT>[0-9]+),\ (?P<CODE>[0-9]+),\ ', line)
		if m is not None:
			filename = m.group("FILE");
			blank    = m.group("BLANK");
			comment  = m.group("COMMENT");
			code     = m.group("CODE");
			lang     = m.group("LANG");

			db.insertfilemetric(project, revision, url, filename, blank, comment, code, lang)
			
	phand.close()
